package com.zs.toolbox.web2j.system.core.config.db;

import com.zs.toolbox.web2j.db.config.WtDbContextHolder;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

/**
 * @author shuai.zhang  on 2018/10/11
 * @description
 */

//@MapperScan({"com.zs.toolbox.web2j.system.user.mapper.user","com.zs.toolbox.web2j.system.user.mapper.other"})
//@within(com.cxh.study.aop.controller.UserAccessAnnotation)
//@annotation(com.cxh.study.aop.controller.UserAccessAnnotation)
@Component
@Aspect
public class WtDataSourceInterceptor {
    Logger logger = LoggerFactory.getLogger(WtDataSourceInterceptor.class);

    @Pointcut(value = "execution(public * com.zs.toolbox.web2j.system.core.mapper.**.*(..)) ||" +
            "execution(public * com.zs.toolbox.web2j.system.core.service.**.save*(..))")
    private void userDataSourceServicePointcut() {
    }
/*
    @Pointcut(value = "execution(public * com.zs.toolbox.web2j.system.user.mapper.other.**.*(..))")
    private void commonDataSourceServicePointcut() {
    }*/

    @Pointcut(value = "@annotation(com.zs.toolbox.web2j.db.config.OnlyReadDbOperation) ||" +
            "execution(public * com.zs.toolbox.web2j.system.core.service.**.get*(..)) ||" +
            "execution(public * com.zs.toolbox.web2j.system.core.service.**.list*(..)) ||" +
            "execution(public * com.zs.toolbox.web2j.system.core.service.**.page*(..))"
    )
    private void onlyReadDBOperationPointcut() {
    }

    /**
     * 切换数据源1
     */
    @Before("onlyReadDBOperationPointcut()")
    public void onlyReadBeforeInterceptor() {
        logger.debug("设置当前方式为完全只读操作");
        WtDbContextHolder.setOnlyRead();
    }

    @After("onlyReadDBOperationPointcut()")
    public void ReadAfterInterceptor() {
        logger.debug("清除完全只读操作");
        WtDbContextHolder.clearOnlyRead();
    }

    /**
     * 切换数据源1
     */
    @Before("userDataSourceServicePointcut()")
    public void dataSource1Interceptor() {
        logger.debug("切换到数据源{}..............................", "datasource-user");
        WtDbContextHolder.setDbType(DBTypeEnum.DB_USER_DATASOURCE.getValue());
    }

/*
    *//**
     * 切换数据源2
     *//*
    @Before("commonDataSourceServicePointcut()")
    public void dataSource2Interceptor() {
        logger.debug("切换到数据源{}.......................", "datasource-common");
        WtDbContextHolder.setDbType(DBTypeEnum.DB_COMMON_DATASOURCE.getValue());
    }*/
}
